package com.stylefeng.guns.rest.modular.order;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.api.cinema.CinemaServiceApi;
import com.stylefeng.guns.api.cinema.vo.FilmInfoVo;
import com.stylefeng.guns.api.cinema.vo.HallInfoVo;
import com.stylefeng.guns.api.cinema.vo.OrderQueryVo;
import com.stylefeng.guns.api.order.OrderServiceApi;
import com.stylefeng.guns.api.order.vo.OrderVo;
import com.stylefeng.guns.api.util.UUIDUtil;
import com.stylefeng.guns.rest.common.persistence.mapper.MoocOrder2017TMapper;
import com.stylefeng.guns.rest.common.persistence.mapper.MoocOrder2018TMapper;
import com.stylefeng.guns.rest.common.persistence.mapper.MoocOrderTMapper;
import com.stylefeng.guns.rest.common.persistence.model.MoocOrderT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName OrderApiServiceImpl
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/9/18  0:42
 * @Version 1.0
 */

@Component
@Service(interfaceClass = OrderServiceApi.class, group = "default")
@Slf4j
public class OrderServiceApiImpl implements OrderServiceApi {

    @Autowired
    private MoocOrderTMapper moocOrderTMapper;

    //两个微服务间的内部调用

    //注解的方式没有实现 分组聚合
    @Reference(interfaceClass = CinemaServiceApi.class, check = false)
    private CinemaServiceApi cinemaServiceApi;


    private String seatsObject = "{\n" +
            "  \"limit\": 5,\n" +
            "  \"ids\":\"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24\",\n" +
            "  \"single\": [\n" +
            "    [\n" +
            "      {\n" +
            "        \"seatId\": 1,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 1\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 2,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 2\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 3,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 3\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 4,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 4\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 5,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 5\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 6,\n" +
            "        \"row\"   : 1,\n" +
            "        \"column\": 6\n" +
            "      }\n" +
            "    ],\n" +
            "    [\n" +
            "      {\n" +
            "        \"seatId\": 7,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 1\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 8,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 2\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 9,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 3\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 10,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 4\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 11,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 5\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 12,\n" +
            "        \"row\"   : 2,\n" +
            "        \"column\": 6\n" +
            "      }\n" +
            "    ]\n" +
            "  ],\n" +
            "  \"couple\": [\n" +
            "    [\n" +
            "      {\n" +
            "        \"seatId\": 13,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 1\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 14,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 2\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 15,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 3\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 16,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 4\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 17,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 5\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 18,\n" +
            "        \"row\"   : 3,\n" +
            "        \"column\": 6\n" +
            "      }\n" +
            "    ],\n" +
            "    [\n" +
            "      {\n" +
            "        \"seatId\": 19,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 1\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 20,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 2\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 21,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 3\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 22,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 4\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 23,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 5\n" +
            "      },\n" +
            "      {\n" +
            "        \"seatId\": 24,\n" +
            "        \"row\"   : 4,\n" +
            "        \"column\": 6\n" +
            "      }\n" +
            "    ]\n" +
            "  ]\n" +
            "}";


    /**
     * 验证是否为真实的手机号
     *
     * @param fieldId 电影id
     * @param seats   座位号
     * @return
     */
    @Override
    public boolean isTrueSeats(String fieldId, String seats) {
        // 根据 fieldId 找到对应的 座位位置图 （此时这个接口 需要跨服务调用了）
        String seatPath = moocOrderTMapper.getSeatsByFieldId(fieldId);

        // 读取位置图 判断seats是否为真
        //将作为转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(seatsObject);
        log.info(" 转换的json对象为 --> " + jsonObject);
        String ids = jsonObject.getString("ids");
        log.info(" 解析出来的 字符串为 --> " + ids);
        //把json中的字符串 转换为字符串数组，只要有一个对不上 返回就是false
        String[] seatsArrs = seats.split(",");
        String[] idArrs = ids.split(",");

        int falg = 0;
        for (String idArr : idArrs) {
            for (String seatsArr : seatsArrs) {
                if (seatsArr.equalsIgnoreCase(idArr)) {
                    falg++;
                }
            }
        }
        if (seatsArrs.length == falg) {
            return true;
        }
        return false;
    }

    //判断是否为已售座位。
    @Override
    public boolean isNotSoldSeats(String fieldId, String seats) {

        EntityWrapper<MoocOrderT> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("field_id", fieldId);

        //衡专纵 逗号分隔 做拼接 用二分
        List<MoocOrderT> moocOrderTS = moocOrderTMapper.selectList(entityWrapper);
        String[] split = seats.split(",");

        for (MoocOrderT moocOrderT : moocOrderTS) {
            String[] ids = moocOrderT.getSeatsIds().split(",");
            for (String id : ids) {
                for (String s : split) {
                    if (id.equalsIgnoreCase(s)) {
                        return false;
                    }
                }
            }
        }


        return true;
    }

    //创建新的订单
    @Override
    public OrderVo saveOrderInfo(Integer fieldId, String soldSeats, String seatsName, Integer userId) {

        String uuid = UUIDUtil.genUuid();

        //获取影片信息
        FilmInfoVo filmFieldInfo = cinemaServiceApi.getFilmInfoByFieldId(fieldId);
        int filmId = Integer.parseInt(filmFieldInfo.getFilmId());

        //获取影院信息
        OrderQueryVo orderNeed = cinemaServiceApi.getOrderNeed(fieldId);
        int cinemaId = Integer.parseInt(orderNeed.getCinemaId());
        double filmPrice = Double.parseDouble(orderNeed.getFilmPrice());

        //求订单总金额
        int solds = soldSeats.split(",").length;
        double totalPrice = getTotalPrice(solds, filmPrice);

        MoocOrderT moocOrderT = new MoocOrderT();
        moocOrderT.setUuid(uuid);
        moocOrderT.setSeatsName(seatsName);
        moocOrderT.setSeatsIds(soldSeats);
        moocOrderT.setOrderUser(userId);
        moocOrderT.setOrderPrice(totalPrice);
        moocOrderT.setFilmPrice(filmPrice);
        moocOrderT.setFilmId(filmId);
        moocOrderT.setFieldId(fieldId);
        moocOrderT.setCinemaId(cinemaId);

        Integer insert = moocOrderTMapper.insert(moocOrderT);
        if (insert > 0) {
            //返回查询结果
            OrderVo orderIdById = moocOrderTMapper.getOrderIdById(uuid);
            if (orderIdById == null) {
                log.error("订单生成失败,插入数据时 可能有失败");
                return null;
            } else {
                return orderIdById;
            }

        } else {
            //插入出错
            log.error("订单生成失败");
            return null;
        }

    }


    private double getTotalPrice(int solds, double filmPrice) {
        BigDecimal soldDecimal = new BigDecimal(solds);
        BigDecimal filmPriceDeci = new BigDecimal(filmPrice);

        BigDecimal resultDeci = soldDecimal.multiply(filmPriceDeci);
        return resultDeci.setScale(2, RoundingMode.FLOOR).doubleValue();
    }

    public static void main(String[] args) {
//        double totalPrice = getTotalPrice(2, 12.2233);
//        System.out.println(totalPrice);
    }


    @Override
    public Page<OrderVo> getOrderByUserId(Integer userId, Page<OrderVo> page) {
        Page<OrderVo> listPage = new Page<>();

        if (userId == null) {
            return null;
        } else {
            List<OrderVo> orderInfoById = moocOrderTMapper.getOrderInfoById(userId, page);
            log.info("查询用户 购票集合 大小 orderInfoById seize --> " + orderInfoById.size());

            if (orderInfoById == null && orderInfoById.size() == 0) {
                listPage.setTotal(0);
                listPage.setRecords(new ArrayList<>());
                return listPage;
            } else {
                //根据用户id 获取订单总数
                EntityWrapper<MoocOrderT> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq("order_user", userId);
                List<MoocOrderT> moocOrderTS = moocOrderTMapper.selectList(entityWrapper);
                log.info("根据用户id 获取 用户的订单集合 --> {}", moocOrderTS);
                Integer count = moocOrderTMapper.selectCount(entityWrapper);
                log.info("根据用户id 获取 用户的订单总数 --> {}", count);

                listPage.setTotal(count);
                listPage.setRecords(orderInfoById);

                return listPage;
            }

        }
    }

    //纵表转横标
    @Override
    public String getSoldSeatsByFieldId(Integer fieldId) {
        if (fieldId == null) {
            log.error("查询已售座位错误，未传入任何场次编号");
            return "";
        }

        return moocOrderTMapper.getSoldSeatsByFieldId(fieldId);
    }

    @Override
    public OrderVo getOrderInfoById(String orderId) {
        OrderVo orderIdById = moocOrderTMapper.getOrderIdById(orderId);
        return orderIdById;
    }

    @Override
    public boolean paySuccess(String orderId) {
//        MoocOrder2018T moocOrderT = new MoocOrder2018T();
//        moocOrderT.setUuid(orderId);
//        moocOrderT.setOrderStatus(1);

        Integer integer = moocOrderTMapper.updateByStringId(orderId);
        if (integer > 0) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public boolean payFail(String orderId) {
//        MoocOrder2018T moocOrderT = new MoocOrder2018T();
//        moocOrderT.setUuid(orderId);
//        moocOrderT.setOrderStatus(2);

        Integer integer = moocOrderTMapper.updateByStringPayFailId(orderId);
        if (integer > 0) {
            return true;
        } else {
            return false;
        }
    }
}
